/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.webfis.persistencia;

import br.com.caelum.vraptor.ioc.Component;
import br.com.webfis.modelos.Destinatario;
import java.util.List;
import javax.persistence.NoResultException;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author silvio
 */
@Component
public class DestinatarioDAO {
    private final Session session;

    public DestinatarioDAO(Session session) {
        this.session = session; 
    }

    public void salvar(Destinatario destinatario) {
        //Transaction tx = session.beginTransaction();
        try {
            session.save(destinatario);
            //tx.commit();
        } catch (HibernateException exp) {
            //tx.rollback();
        }
    }
    
    public void atualizar(Destinatario destinatario) {
        try {
            session.update(destinatario);
        } catch (HibernateException exp) {
            //
        }
    }
    
    public void deletar(Destinatario destinatario) {
        try {
            session.delete(destinatario);
        } catch (HibernateException exp) {
            //
        }
    }
    
    public List<Destinatario> listaTudo() {
            return this.session.createCriteria(Destinatario.class).list();           
        }

    public List<Destinatario> Pesquisar(Integer id, String texto) {
        List<Destinatario> resultado;
        try {
            Criteria criterio = this.session.createCriteria(Destinatario.class);
            if (id > 0)
                criterio.add( Restrictions.eq("idDestinatario", id) ); 
            else
                criterio.add( Restrictions.ilike("destinatario", texto, MatchMode.ANYWHERE) );             
            
            resultado= criterio.list();

            return resultado;
            
        } catch (NoResultException e) {
            return null;
        }
    }
}
